requirejs.config({
    baseUrl: './',
    paths: {
        "jquery": ["/common/vendor/jquery-2.1.4/jquery-2.1.4.min"],
        "base": ["/common/scripts/base"],
        "ajax": ["/common/scripts/ajax"],
        "swiper": ["/common/vendor/swiper-left-ios/swiper.min"],
        "laydate": ['js/calendar-bottom'],
        "local": "/common/scripts/local",
        "file": ["/common/scripts/file"]
    },
    shim: {
        "laydate": {
            deps: ["jquery", "swiper"],
            exports: 'laydate'
        },
        "swiper": {
            deps: ["jquery"],
            exports: 'swiper'
        }
    }
});
require(["jquery", "base", "ajax", "laydate","local", "file"], function($, base, ajax, laydate, local,fill) {
    "use strict";
    var beginTime = '',
        endTime = '',
        timer = null,
        marketCode = base.getUrlParameter('marketCode') || '', //市场代码
        currency = base.getUrlParameter('currency') || '401156', //401156 人民币 401344  港元 401840 美元
        source = base.getUrlParameter('source') || '150001', //系统源 150001 普通 150002 信用  150003 限售股 150000 全账户
        type = base.getUrlParameter('type') || 0, // 0 首页  1 个股首页跳入
        stockCode = base.getUrlParameter('stockCode') || '', //股票代码
        dateType = "00",
        index = 0,//点击确定后 准备首页数据或是个股首页数据  最多调用4次
        toastTimer = null,//定时器
        loadTimer = null,
        account = "",
        urltype = "";
    var custom = {
        init: function() {
            var self = this;
            local.read({
                P_SOURCE: "", //系统源 150001 普通 150     002 信用  150003 限售股 150000 全账户
                P_CURRENCY: "", //401156 人民币 401344  港元 401840 美元
                P_ACCOUNT:""
            }, function(_obj) {
                var str = _obj.P_CURRENCY;
                switch (str){
                    case '港币':{
                        currency = '401344';
                        break;
                    }
                    case '美元':{
                        currency = '401840';
                        break;
                    }
                    case '元':{
                        currency = '401156';
                        break;
                    }
                    default:{
                        currency = '401156';
                        break;
                    }
                }
                if(type == 0){
                    source = _obj.P_SOURCE;
                }
                account = _obj.P_ACCOUNT;
                urltype = {
                    0: '/reqxml?action=27401&path=/account/hold_analysis/hold_analysis_index_one?dateType='+dateType+'&clientNo='+account+'&currency=' + currency + '&source=' + source,
                    1: '/reqxml?action=27401&path=/account/hold_analysis/single_stock_explain?isGetNotification=1&dateType='+dateType+'&clientNo='+account+'&stockCode=' + stockCode + '&marketCode=' + marketCode + '&currency=' + currency + '&source=' + source
                };
                TalkingData.onHTSCEvent("page", "leaf304", "持仓综合分析_自定义时间段 ", "", "")
                self.getMaxEndDate();
                self.bindEvent();
            })
        },
        getMaxEndDate:function(){
            var self = this,
                url = '/reqxml?action=27006&path=/account/hold_analysis/get_date',
                endDate = '';
            ajax.run(url, '', function(data) {
                if (data && data.BINDATA) {
                    var data = JSON.parse(data.BINDATA),
                        obj = data.data,
                        code = data.code,
                        msg = data.msg;
                    if (code === "0") {
                        if(obj.date && obj.date != ''){
                            var year = obj.date.split('/')[0],
                                month = obj.date.split('/')[1],
                                day = obj.date.split('/')[2];
                            endTime = obj.date;
                            beginTime = (year - 2) + '/' + month + '/' + day;
                        }else{
                            self.getStartDate();
                        }
                    } else {
                        self.getStartDate();
                    }
                } else {
                    self.getStartDate();
                }
            }, function(obj) {
                self.getStartDate();
            });
        },
        /**
         * [getStartDate 获取本地时间 向前推3年为开始时间]
         * @return {[type]} [description]
         */
        getStartDate: function() {
            var self = this,
                year = new Date().getFullYear(),
                _month = new Date().getMonth() + 1,
                month = self.addZero(_month),
                _date = new Date().getDate(),
                date = '';
            //如果当前年份为闰年 并且 日期是最后一天  那么3年前的日期  如果为闰年 那么也是28  非闰年为29
            if (year / 4 == 0 && _date == '28') {
                if ((year - 2) / 4 == 0) {
                    date = _date;
                } else {
                    date = '29';
                }
            }else{
                date = _date;
            }
            //如果当前年份非闰年 并且日期也是最后一天  那么3年前的如期如果为闰年 那么是28  非闰年还是29
            if (year / 4 != 0 && _date == '29') {
                if ((year - 2) / 4 == 0) {
                    date = '28';
                } else {
                    date = _date;
                }
            }else{
                date = _date;
            }
            beginTime = (year - 2) + '/' + month + '/' + date,
            endTime = year + '/' + month + '/' + (date-1);
        },
        /**
         * [calendarInit 日历控件初始化]
         * @param  {[type]} id    [选择时间后显示的页面元素id]
         * @param  {[type]} curdate  [当前选择时间]
         * @param  {[type]} begin [开始时间(最小时间)]
         * @param  {[type]} end   [结束时间(最大时间)]
         * @return {[type]}       [description]
         */
        calendarInit: function(id, curdate, begin, end, startEmpty,callback) {
            var self = this;
            laydate.init({
                date: { //起始时间
                    year: curdate.year,
                    month: curdate.month,
                    day: curdate.day
                },
                curDate: { //当日
                    year: curdate.year,
                    month: curdate.month,
                    day: curdate.day
                },
                startEmpty:startEmpty,
                //最小时间
                min: new Date(begin).getTime(),
                //最大时间
                max: new Date(end).getTime(),
                callback: function(date) {
                    $("#" + id).val(date.year + "/" + self.addZero(date.month) + "/" + self.addZero(date.day));
                    callback && callback(date);
                }
            });
        },
        /**
         * [getData description]
         * @param  {[type]} url    [请求url]
         * @param  {[type]} params [请求参数]
         * @return {[type]}        [description]
         */
        getData: function(url, params,date) {
            base.log('index=='+index);
            index++;
            var dtd = $.Deferred();
            ajax.run(url, params, function(data) {
                try {
                    var json = JSON.parse(data.BINDATA);
                    var flag = json.code,
                        mes = json.msg,
                        isReady = json.data.isReady;
                    if (flag === "0") {
                        if (isReady && isReady == 1) {
                            dtd.resolve(json.data);
                        } else {
                            if(index < 5){
                                if (timer) {
                                    clearTimeout(timer);
                                }
                                timer = setTimeout(function(){
                                    custom.getData(url, params, date).then(function(xml) {
                                        file.insert("positon.js", {
                                            startDate: date.start,
                                            endDate: date.end
                                        }, function(data) {
                                            $('.loading-wrap').hide();
                                            base.href("http://action:3413")
                                        });
                                    });
                                },3000);
                            }else{
                                dtd.reject();
                                $('.loading-wrap').hide();
                                alert('网络异常，请稍后重试');
                            }
                        }
                    } else {
                        if(index < 5){
                            if (timer) {
                                clearTimeout(timer);
                            }
                            timer = setTimeout(function(){
                                custom.getData(url, params,date).then(function(xml) {
                                    file.insert("positon.js", {
                                        startDate: date.start,
                                        endDate: date.end
                                    }, function(data) {
                                        $('.loading-wrap').hide();
                                        base.href("http://action:3413")
                                    });
                                });
                            },3000);
                        }else{
                            dtd.reject();
                            $('.loading-wrap').hide();
                            alert('网络异常，请稍后重试');
                        }
                    }
                } catch (e) {
                    dtd.reject();
                    $('.loading-wrap').hide();
                    alert('网络异常，请稍后重试');
                }
            }, function(xml) {
                dtd.reject();
                $('.loading-wrap').hide();
                xml.ERRORMESSAGE && alert("网络异常，请稍后重试");
            });
            return dtd.promise();
        },
        /**
         * [addZero 不满10加0]
         * @param {[type]} str [字符串]
         */
        addZero: function(str) {
            var month = Number(str);
            if (month < 10) {
                month = '0' + month;
            }
            return month;
        },
        toast: function(str) {
            $(".toast").html(str).fadeIn();
            if(toastTimer){
                clearTimeout(toastTimer);
            }
            toastTimer = setTimeout(function() {
                $(".toast").fadeOut();
            }, 1000);
        },
        /**
         * [bindEvent 事件绑定]
         * @return {[type]} [description]
         */
        bindEvent: function() {
            var self = this;
            $("#date-start").click(function() {
                var start = $('#date-start').val(),
                    end = $("#date-end").val(),
                    val = start && start != '' ? start.split('/') : endTime.split('/'),
                    startEmpty = start && start != '' ? false : true ;
                var date = {
                    year: val[0],
                    month: val[1],
                    day: val[2]
                }
                self.calendarInit('date-start', date, beginTime, endTime,startEmpty,function(date){
                    var end = $('#date-end').val(),
                        _start = date.year + "/" + self.addZero(date.month) + "/" + self.addZero(date.day);
                    if(new Date(_start).getTime() > new Date(end).getTime()){
                        $('#date-end').val('');
                        $(".sure-btn").addClass('unclicked');
                    }
                    //如果重新选择的开始时间 大于半年
                    if(end != ''){
                        var space = new Date(start).getTime() - new Date(_start).getTime();
                        if(space >= 60*24*60*60){
                            $("#date-end").val('');
                            $(".sure-btn").addClass('unclicked');
                        }
                    }
                });
            });
            $("#date-end").click(function() {
                var start = $("#date-start").val();
                var val = $(this).val(),
                    date = {};
                if (!start) {
                    self.toast('请选择开始时间');
                    return;
                }
                if (val && val != '' && val != null && val != undefined) {
                    val = val.split('/');
                } else {
                    val = start.split('/');
                }
                var year = new Date(start).getFullYear(),
                    month = new Date(start).getMonth(),
                    _month = month + 7,
                    _date = new Date(start).getDate(),
                    _end = null;
                if (_month >= 13) {
                    year = year + 1;
                    _month = _month - 12;
                }
                if (_month < 10) {
                    _month = '0' + _month;
                }
                if (_date < 10) {
                    _date = '0' + _date;
                }
                _end = year + '/' + _month + '/' + _date;
                //如果重新选择的开始时间 大于之前的结束时间
                if(new Date(start).getTime() > new Date(val).getTime()){
                    date = {
                        year: year,
                        month: month + 1,
                        day: _date
                    }
                    $('#date-end').val(start);
                }else{
                    date = {
                        year: val[0],
                        month: val[1],
                        day: val[2]
                    }
                }
                if(new Date().getTime() <= new Date(_end).getTime()){
                   _end = endTime;
                }
                self.calendarInit('date-end', date, start, _end, false,function() {
                    $(".sure-btn").removeClass('unclicked');
                });
            });
            $(".sure-btn").click(function() {
                if($(this).hasClass('unclicked')){
                    self.toast('请选择时间哦');
                }else{
                    $('.loading-wrap').show();
                    var start = $("#date-start").val(),
                        end = $("#date-end").val();
                    index = 0;
                    TalkingData.onHTSCEvent("click", "leaf304", "持仓综合分析_自定义时间段", "", "确定|kssj="+start+"|jssj="+end)
                    if (!$(this).hasClass('unclicked')) {
                        custom.getData(urltype[base.getUrlParameter('type')], {
                            startDate: start.replace(/\//ig, ''),
                            endDate: end.replace(/\//ig, '')
                        },{
                            start:start,
                            end:end
                        }).then(function(xml) {
                            file.insert("positon.js", {
                                startDate: start,
                                endDate: end
                            }, function(data) {
                                if(loadTimer){
                                    clearTimeout(loadTimer);
                                }
                                loadTimer = setTimeout(function(){
                                    $('.loading-wrap').hide();
                                    base.href("http://action:3413")
                                }, 2000);
                            });
                        });
                    } 
                }
            });
        }
    }
    custom.init();
});